<?php
require_once 'includes/header.php';
require_once 'includes/DatabaseHelper.php';

require_once 'includes/functions.php';

$db = Database::getInstance();

// 获取统计视图
$view = isset($_GET['view']) ? $_GET['view'] : 'overview';

// 设置时间范围
$timeRange = isset($_GET['time_range']) ? $_GET['time_range'] : 'last_month';
$startDate = '';
$endDate = date('Y-m-d');

switch ($timeRange) {
    case 'today':
        $startDate = date('Y-m-d');
        break;
    case 'yesterday':
        $startDate = date('Y-m-d', strtotime('-1 day'));
        $endDate = $startDate;
        break;
    case 'last_7_days':
        $startDate = date('Y-m-d', strtotime('-6 days'));
        break;
    case 'last_30_days':
        $startDate = date('Y-m-d', strtotime('-29 days'));
        break;
    case 'this_month':
        $startDate = date('Y-m-01');
        break;
    case 'last_month':
        $startDate = date('Y-m-01', strtotime('-1 month'));
        $endDate = date('Y-m-t', strtotime('-1 month'));
        break;
    case 'this_year':
        $startDate = date('Y-01-01');
        break;
    case 'custom':
        $startDate = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-d', strtotime('-29 days'));
        $endDate = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d');
        break;
    default:
        $startDate = date('Y-m-d', strtotime('-29 days'));
}

// 验证日期格式
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $startDate)) {
    $startDate = date('Y-m-d', strtotime('-29 days'));
}

if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $endDate)) {
    $endDate = date('Y-m-d');
}

// 确保开始日期不大于结束日期
if (strtotime($startDate) > strtotime($endDate)) {
    $tmp = $startDate;
    $startDate = $endDate;
    $endDate = $tmp;
}

// 为结束日期添加时间部分，使其包含整天
$endDateWithTime = $endDate . ' 23:59:59';

// 常用统计
$totalUsers = $db->fetchColumn("SELECT COUNT(*) FROM " . DB_PREFIX . "users WHERE role = 'user'");
$totalGames = $db->fetchColumn("SELECT COUNT(*) FROM " . DB_PREFIX . "games");
$totalAchievements = $db->fetchColumn("SELECT COUNT(*) FROM " . DB_PREFIX . "achievements");
$totalGamePlays = $db->fetchColumn("SELECT COUNT(*) FROM " . DB_PREFIX . "game_records");

// 在指定时间范围内的统计
$newUsers = $db->fetchColumn(
    "SELECT COUNT(*) FROM " . DB_PREFIX . "users 
     WHERE role = 'user' AND created_at BETWEEN ? AND ?",
    [$startDate, $endDateWithTime]
);

$activePlayers = $db->fetchColumn(
    "SELECT COUNT(DISTINCT user_id) FROM " . DB_PREFIX . "game_records 
     WHERE played_at BETWEEN ? AND ?",
    [$startDate, $endDateWithTime]
);

$gamePlays = $db->fetchColumn(
    "SELECT COUNT(*) FROM " . DB_PREFIX . "game_records 
     WHERE played_at BETWEEN ? AND ?",
    [$startDate, $endDateWithTime]
);

$achievementsUnlocked = $db->fetchColumn(
    "SELECT COUNT(*) FROM " . DB_PREFIX . "user_achievements 
     WHERE unlocked_at BETWEEN ? AND ?",
    [$startDate, $endDateWithTime]
);

// 获取每日新用户注册数据
$dailyNewUsers = $db->fetchAll(
    "SELECT DATE(created_at) as date, COUNT(*) as count 
     FROM " . DB_PREFIX . "users 
     WHERE role = 'user' AND created_at BETWEEN ? AND ? 
     GROUP BY DATE(created_at) 
     ORDER BY date",
    [$startDate, $endDateWithTime]
);

// 获取每日游戏次数数据
$dailyGamePlays = $db->fetchAll(
    "SELECT DATE(played_at) as date, COUNT(*) as count 
     FROM " . DB_PREFIX . "game_records 
     WHERE played_at BETWEEN ? AND ? 
     GROUP BY DATE(played_at) 
     ORDER BY date",
    [$startDate, $endDateWithTime]
);

// 获取游戏受欢迎程度数据
$popularGames = $db->fetchAll(
    "SELECT g.id, g.name, COUNT(gr.id) as play_count 
     FROM " . DB_PREFIX . "games g 
     LEFT JOIN " . DB_PREFIX . "game_records gr ON g.id = gr.game_id 
     WHERE gr.played_at BETWEEN ? AND ? 
     GROUP BY g.id, g.name 
     ORDER BY play_count DESC 
     LIMIT 10",
    [$startDate, $endDateWithTime]
);

// 获取用户活跃度数据
$activeUsersData = $db->fetchAll(
    "SELECT u.id, u.username, COUNT(gr.id) as play_count 
     FROM " . DB_PREFIX . "users u 
     JOIN " . DB_PREFIX . "game_records gr ON u.id = gr.user_id 
     WHERE gr.played_at BETWEEN ? AND ? 
     GROUP BY u.id, u.username 
     ORDER BY play_count DESC 
     LIMIT 10",
    [$startDate, $endDateWithTime]
);

// 准备图表数据
$chartLabels = [];
$chartNewUsers = [];
$chartGamePlays = [];

// 创建日期范围数组
$period = new DatePeriod(
    new DateTime($startDate),
    new DateInterval('P1D'),
    (new DateTime($endDate))->modify('+1 day')
);

foreach ($period as $date) {
    $dateStr = $date->format('Y-m-d');
    $chartLabels[] = $date->format('m-d');
    
    // 找到该日期的新用户数
    $found = false;
    foreach ($dailyNewUsers as $item) {
        if ($item['date'] == $dateStr) {
            $chartNewUsers[] = (int)$item['count'];
            $found = true;
            break;
        }
    }
    if (!$found) {
        $chartNewUsers[] = 0;
    }
    
    // 找到该日期的游戏次数
    $found = false;
    foreach ($dailyGamePlays as $item) {
        if ($item['date'] == $dateStr) {
            $chartGamePlays[] = (int)$item['count'];
            $found = true;
            break;
        }
    }
    if (!$found) {
        $chartGamePlays[] = 0;
    }
}

// JSON编码图表数据
$chartLabelsJson = json_encode($chartLabels);
$chartNewUsersJson = json_encode($chartNewUsers);
$chartGamePlaysJson = json_encode($chartGamePlays);

// 获取游戏记录列表
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 20;
$offset = ($page - 1) * $perPage;

$gameRecords = $db->fetchAll(
    "SELECT gr.id, gr.user_id, gr.game_id, gr.score, gr.duration, gr.played_at,
            u.username, g.name as game_name
     FROM " . DB_PREFIX . "game_records gr
     JOIN " . DB_PREFIX . "users u ON gr.user_id = u.id
     JOIN " . DB_PREFIX . "games g ON gr.game_id = g.id
     WHERE gr.played_at BETWEEN ? AND ?
     ORDER BY gr.played_at DESC
     LIMIT ?, ?",
    [$startDate, $endDateWithTime, $offset, $perPage]
);

$totalRecords = $db->fetchColumn(
    "SELECT COUNT(*) FROM " . DB_PREFIX . "game_records
     WHERE played_at BETWEEN ? AND ?",
    [$startDate, $endDateWithTime]
);

$totalPages = ceil($totalRecords / $perPage);
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1><i class="bi bi-bar-chart"></i> 数据统计</h1>
</div>

<!-- 时间范围选择 -->
<div class="card mb-4">
    <div class="card-body">
        <form action="" method="get" class="row g-3 align-items-end">
            <input type="hidden" name="view" value="<?php echo htmlspecialchars($view); ?>">
            
            <div class="col-md-3">
                <label for="time_range" class="form-label">时间范围</label>
                <select class="form-select" id="time_range" name="time_range" onchange="toggleCustomDateInputs()">
                    <option value="today" <?php echo $timeRange == 'today' ? 'selected' : ''; ?>>今天</option>
                    <option value="yesterday" <?php echo $timeRange == 'yesterday' ? 'selected' : ''; ?>>昨天</option>
                    <option value="last_7_days" <?php echo $timeRange == 'last_7_days' ? 'selected' : ''; ?>>过去7天</option>
                    <option value="last_30_days" <?php echo $timeRange == 'last_30_days' ? 'selected' : ''; ?>>过去30天</option>
                    <option value="this_month" <?php echo $timeRange == 'this_month' ? 'selected' : ''; ?>>本月</option>
                    <option value="last_month" <?php echo $timeRange == 'last_month' ? 'selected' : ''; ?>>上月</option>
                    <option value="this_year" <?php echo $timeRange == 'this_year' ? 'selected' : ''; ?>>今年</option>
                    <option value="custom" <?php echo $timeRange == 'custom' ? 'selected' : ''; ?>>自定义范围</option>
                </select>
            </div>
            
            <div class="col-md-3 custom-date-input" style="display: <?php echo $timeRange == 'custom' ? 'block' : 'none'; ?>;">
                <label for="start_date" class="form-label">开始日期</label>
                <input type="date" class="form-control" id="start_date" name="start_date" value="<?php echo $startDate; ?>">
            </div>
            
            <div class="col-md-3 custom-date-input" style="display: <?php echo $timeRange == 'custom' ? 'block' : 'none'; ?>;">
                <label for="end_date" class="form-label">结束日期</label>
                <input type="date" class="form-control" id="end_date" name="end_date" value="<?php echo $endDate; ?>">
            </div>
            
            <div class="col-md-3">
                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-search"></i> 应用筛选
                </button>
            </div>
        </form>
    </div>
</div>

<!-- 统计选项卡 -->
<ul class="nav nav-tabs mb-4">
    <li class="nav-item">
        <a class="nav-link <?php echo $view == 'overview' ? 'active' : ''; ?>" href="stats.php?view=overview&time_range=<?php echo $timeRange; ?>&start_date=<?php echo $startDate; ?>&end_date=<?php echo $endDate; ?>">
            <i class="bi bi-graph-up"></i> 概览
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link <?php echo $view == 'users' ? 'active' : ''; ?>" href="stats.php?view=users&time_range=<?php echo $timeRange; ?>&start_date=<?php echo $startDate; ?>&end_date=<?php echo $endDate; ?>">
            <i class="bi bi-people"></i> 用户分析
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link <?php echo $view == 'games' ? 'active' : ''; ?>" href="stats.php?view=games&time_range=<?php echo $timeRange; ?>&start_date=<?php echo $startDate; ?>&end_date=<?php echo $endDate; ?>">
            <i class="bi bi-controller"></i> 游戏分析
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link <?php echo $view == 'achievements' ? 'active' : ''; ?>" href="stats.php?view=achievements&time_range=<?php echo $timeRange; ?>&start_date=<?php echo $startDate; ?>&end_date=<?php echo $endDate; ?>">
            <i class="bi bi-trophy"></i> 成就分析
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link <?php echo $view == 'game_records' ? 'active' : ''; ?>" href="stats.php?view=game_records&time_range=<?php echo $timeRange; ?>&start_date=<?php echo $startDate; ?>&end_date=<?php echo $endDate; ?>">
            <i class="bi bi-list-check"></i> 游戏记录
        </a>
    </li>
</ul>

<?php if ($view == 'overview'): ?>
<!-- 概览视图 -->
<div class="row">
    <!-- 统计卡片 -->
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card border-left-primary shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">新注册用户</div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($newUsers); ?></div>
                        <div class="small text-muted">总用户数: <?php echo number_format($totalUsers); ?></div>
                    </div>
                    <div class="col-auto">
                        <i class="bi bi-person-plus fs-2"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card border-left-success shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-success text-uppercase mb-1">活跃玩家</div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($activePlayers); ?></div>
                        <div class="small text-muted">期间内有游戏记录的用户</div>
                    </div>
                    <div class="col-auto">
                        <i class="bi bi-people fs-2"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card border-left-info shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-info text-uppercase mb-1">游戏次数</div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($gamePlays); ?></div>
                        <div class="small text-muted">总游戏次数: <?php echo number_format($totalGamePlays); ?></div>
                    </div>
                    <div class="col-auto">
                        <i class="bi bi-controller fs-2"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card border-left-warning shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">解锁成就</div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($achievementsUnlocked); ?></div>
                        <div class="small text-muted">总成就数: <?php echo number_format($totalAchievements); ?></div>
                    </div>
                    <div class="col-auto">
                        <i class="bi bi-trophy fs-2"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 趋势图表 -->
<div class="row">
    <div class="col-lg-12">
        <div class="card mb-4">
            <div class="card-header">
                <i class="bi bi-graph-up me-1"></i> 用户注册和游戏活跃度趋势
                <div class="small text-muted d-inline-block ms-2">
                    <?php echo date('Y-m-d', strtotime($startDate)) . ' 至 ' . date('Y-m-d', strtotime($endDate)); ?>
                </div>
            </div>
            <div class="card-body">
                <canvas id="trendChart" height="300"></canvas>
            </div>
        </div>
    </div>
</div>

<!-- 受欢迎游戏和活跃用户 -->
<div class="row">
    <div class="col-lg-6">
        <div class="card mb-4">
            <div class="card-header">
                <i class="bi bi-controller me-1"></i> 最受欢迎游戏
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered table-hover">
                        <thead>
                            <tr>
                                <th>游戏名称</th>
                                <th>游玩次数</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($popularGames)): ?>
                                <?php foreach ($popularGames as $game): ?>
                                <tr>
                                    <td>
                                        <a href="game_detail.php?id=<?php echo $game['id']; ?>">
                                            <?php echo htmlspecialchars($game['name']); ?>
                                        </a>
                                    </td>
                                    <td><?php echo number_format($game['play_count']); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="2" class="text-center">该时间段内没有游戏记录</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-lg-6">
        <div class="card mb-4">
            <div class="card-header">
                <i class="bi bi-person-check me-1"></i> 最活跃用户
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered table-hover">
                        <thead>
                            <tr>
                                <th>用户名</th>
                                <th>游玩次数</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($activeUsersData)): ?>
                                <?php foreach ($activeUsersData as $user): ?>
                                <tr>
                                    <td>
                                        <a href="user_detail.php?id=<?php echo $user['id']; ?>">
                                            <?php echo htmlspecialchars($user['username']); ?>
                                        </a>
                                    </td>
                                    <td><?php echo number_format($user['play_count']); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="2" class="text-center">该时间段内没有活跃用户</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 加载图表库 -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.7.1/dist/chart.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 趋势图表初始化
    const trendCtx = document.getElementById('trendChart').getContext('2d');
    const trendChart = new Chart(trendCtx, {
        type: 'line',
        data: {
            labels: <?php echo $chartLabelsJson; ?>,
            datasets: [
                {
                    label: '新注册用户',
                    data: <?php echo $chartNewUsersJson; ?>,
                    backgroundColor: 'rgba(78, 115, 223, 0.2)',
                    borderColor: 'rgba(78, 115, 223, 1)',
                    pointBackgroundColor: 'rgba(78, 115, 223, 1)',
                    borderWidth: 2,
                    tension: 0.1
                },
                {
                    label: '游戏次数',
                    data: <?php echo $chartGamePlaysJson; ?>,
                    backgroundColor: 'rgba(28, 200, 138, 0.2)',
                    borderColor: 'rgba(28, 200, 138, 1)',
                    pointBackgroundColor: 'rgba(28, 200, 138, 1)',
                    borderWidth: 2,
                    tension: 0.1
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
});
</script>

<?php elseif ($view == 'game_records'): ?>
<!-- 游戏记录视图 -->
<div class="card mb-4">
    <div class="card-header">
        <i class="bi bi-list-check me-1"></i> 游戏记录
        <span class="badge bg-info ms-2"><?php echo number_format($totalRecords); ?> 条记录</span>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered table-hover">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>用户</th>
                        <th>游戏</th>
                        <th>分数</th>
                        <th>游戏时长</th>
                        <th>游玩时间</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($gameRecords)): ?>
                        <?php foreach ($gameRecords as $record): ?>
                        <tr>
                            <td><?php echo $record['id']; ?></td>
                            <td>
                                <a href="user_detail.php?id=<?php echo $record['user_id']; ?>">
                                    <?php echo htmlspecialchars($record['username']); ?>
                                </a>
                            </td>
                            <td>
                                <a href="game_detail.php?id=<?php echo $record['game_id']; ?>">
                                    <?php echo htmlspecialchars($record['game_name']); ?>
                                </a>
                            </td>
                            <td><?php echo number_format($record['score']); ?></td>
                            <td><?php echo $record['duration'] ? formatDuration($record['duration']) : '-'; ?></td>
                            <td><?php echo date('Y-m-d H:i:s', strtotime($record['played_at'])); ?></td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="6" class="text-center">该时间段内没有游戏记录</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <!-- 分页 -->
    <?php if ($totalPages > 1): ?>
    <div class="card-footer">
        <nav>
            <ul class="pagination justify-content-center mb-0">
                <?php
                // 分页导航
                renderPagination($page, $totalPages, 'stats.php', [
                    'view' => 'game_records',
                    'time_range' => $timeRange,
                    'start_date' => $startDate,
                    'end_date' => $endDate
                ]);
                ?>
            </ul>
        </nav>
    </div>
    <?php endif; ?>
</div>
<?php endif; ?>

<script>
function toggleCustomDateInputs() {
    const timeRange = document.getElementById('time_range').value;
    const customDateInputs = document.querySelectorAll('.custom-date-input');
    
    customDateInputs.forEach(input => {
        input.style.display = timeRange === 'custom' ? 'block' : 'none';
    });
}
</script>

<?php
/**
 * 格式化持续时间（秒）为人类可读格式
 * 
 * @param int $seconds 秒数
 * @return string 格式化后的时间
 */
function formatDuration($seconds) {
    if ($seconds < 60) {
        return $seconds . "秒";
    } elseif ($seconds < 3600) {
        $minutes = floor($seconds / 60);
        $secs = $seconds % 60;
        return $minutes . "分" . ($secs > 0 ? $secs . "秒" : "");
    } else {
        $hours = floor($seconds / 3600);
        $minutes = floor(($seconds % 3600) / 60);
        return $hours . "小时" . ($minutes > 0 ? $minutes . "分" : "");
    }
}

require_once 'includes/footer.php';
?> 